from fastapi import APIRouter, Depends, Body
from fastapi.responses import RedirectResponse
from pydantic import HttpUrl
from sqlalchemy.orm import Session

from app.tools_url_shorten.handlers import create_short_link
from app.tools_url_shorten.models import ToolsShortenedUrl
from common.database import get_db
from core.response import resp_200, resp_404

router = APIRouter()


@router.post('/short', summary="原网址转换短地址", description="工具-短域名转换")
async def post_short_link(db: Session = Depends(get_db), original_url: HttpUrl = Body(..., embed=True)):
    short_link = create_short_link(db, original_url)
    return resp_200({'short_link': short_link})


@router.get('/original', summary="短地址查找原网址", description="工具-短域名转换")
async def get_short_original_url(short_link: str, db: Session = Depends(get_db)):
    obj = db.query(ToolsShortenedUrl).with_entities(ToolsShortenedUrl.original_url).filter_by(short_link=short_link).first()
    if not obj:
        return resp_404(message='The link does not exist, could not redirect.')
    return resp_200({'short_link': obj.original_url})


@router.get('/redirect', summary="短地址重定向原网址", description="工具-短域名转换")
async def get_short_redirect(short_link: str, db: Session = Depends(get_db)):
    obj = db.query(ToolsShortenedUrl).filter_by(short_link=short_link).first()
    if not obj:
        return resp_404(message='The link does not exist, could not redirect.')
    return RedirectResponse(url=obj.original_url)
